package com.slipper.system.login;

import com.slipper.common.bo.Result;
import com.slipper.common.util.*;
import com.slipper.system.api.employee.bo.EmployeeBO;
import com.slipper.system.api.employee.service.IEmployeeSv;
import com.slipper.system.api.log.bo.LoginLogBO;
import com.slipper.system.api.menu.bo.MenuBO;
import com.slipper.system.api.menu.service.IMenuSv;
import com.slipper.system.api.role.bo.RoleBO;
import com.slipper.system.api.role.service.IRoleSv;
import com.slipper.system.common.Constants;
import com.slipper.system.common.UserDetail;
import com.slipper.system.log.LogAsyncService;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class LoginController {
    @Resource
    private IMenuSv menuSv;
    @Resource
    private IRoleSv roleSv;
    @Resource
    private IEmployeeSv employeeSv;
    @Resource
    private LogAsyncService logAsyncService;

    @PostMapping("/login")
    public String login(HttpServletRequest request, @RequestBody EmployeeBO bo) throws Exception {
        String captcha = Constants.getAndCleanCaptcha();
        if (captcha != null && (bo.getCaptcha() == null || "".equals(bo.getCaptcha())
                || !bo.getCaptcha().equalsIgnoreCase(captcha))) {
            return ResultUtil.toErrorJson("验证码不正确！");
        }

        Result<EmployeeBO> employeeResult = this.employeeSv.queryByLogin(bo);
        if (!employeeResult.isSuccess() || employeeResult.getData() == null) {
            return com.slipper.common.util.ResultUtil.toErrorJson("账号错误！");
        }

        bo.setPassword(RSAUtil.decrypt(bo.getPassword(), Constants.getRSAKey().getPrivateKey()));
        EmployeeBO employee = employeeResult.getData();
        if (!MD5.encode(bo.getPassword()).equals(employee.getPassword())) {
            return ResultUtil.toErrorJson("密码错误！");
        }

        UserDetail userDetail = new UserDetail();
        userDetail.setEmployee(employee);
        userDetail.setSuperAdmin(this.roleSv.isSuperAdmin(employee.getId()).getData());
        employee.setSuperAdmin(userDetail.isSuperAdmin());

        employee.setOrgId(userDetail.getOrgId());
        employee.setOrgName(userDetail.getOrgName());
        employee.setOrgType(userDetail.getOrgType());

        if (!userDetail.isSuperAdmin()) {
            MenuBO menuBO = new MenuBO();
            menuBO.setEmployeeId(employee.getId());
            userDetail.setPermitSet(this.menuSv.queryPermitUrl(menuBO).getData());
        }

        LoginLogBO loginLog = new LoginLogBO();
        loginLog.setOrgId(userDetail.getOrgId());
        loginLog.setOrgName(userDetail.getOrgName());
        loginLog.setUserId(employee.getId());
        loginLog.setUserName(employee.getName());
        loginLog.setLoginTime(new Date());
        loginLog.setIpAddress(Tool.getIpAddr(request));
        loginLog.setBrowerInfo(request.getHeader("User-Agent"));
        loginLog.setLoginType("浏览器登录");
        loginLog.setOperateInfo("登录成功！");
        this.logAsyncService.saveLoginLog(loginLog);

        RoleBO roleQO = new RoleBO();
        roleQO.setEmployeeId(employee.getId());
        Result<List<RoleBO>> roleList = this.roleSv.queryList(roleQO);
        if (!roleList.isSuccess() || roleList.getData().isEmpty()) {
            return ResultUtil.toErrorJson("账号未配置角色，请先配置！");
        }

        employee.setRoleNames(
                roleList.getData()
                        .stream()
                        .map(RoleBO::getName)
                        .collect(Collectors.joining(",")));
        employee.setRoleId(roleList.getData().get(0).getId());
        employee.setToken(Tool.getUUID());
        Constants.setCurrentUser(userDetail);

        return ResultUtil.toJson(employee);
    }

    @PostMapping("/loginSalt")
    public String loginSalt() {
        return ResultUtil.toJson(Constants.getRSAKey().getPublicKey());
    }

    @PostMapping("/loginInfo")
    public String loginInfo() {
        return ResultUtil.toJson(Constants.getCurrentUser().getEmployee());
    }

    @PostMapping("/logoutUser")
    public String logoutUser(HttpServletRequest request) {
        UserDetail userDetail = Constants.getCurrentUser();
        LoginLogBO loginLog = new LoginLogBO();
        loginLog.setOrgId(userDetail.getOrgId());
        loginLog.setOrgName(userDetail.getOrgName());
        loginLog.setUserId(userDetail.getEmployee().getId());
        loginLog.setUserName(userDetail.getEmployee().getName());
        loginLog.setLoginTime(new Date());
        loginLog.setIpAddress(Tool.getIpAddr(request));
        loginLog.setLoginType("浏览器登录");
        loginLog.setBrowerInfo(request.getHeader("User-Agent"));
        loginLog.setOperateInfo("退出登录！");
        this.logAsyncService.saveLoginLog(loginLog);

        Constants.getCurrentRequest().getSession().invalidate();
        return ResultUtil.toSuccessJson("退出登录成功！");
    }
}
